package com.itouch.bracelet.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.ViewfinderView;
import com.itouch.bracelet.R;

public class QrCodeActivity extends CaptureActivity implements OnClickListener {

	private ImageView back;
	private static final int REQUEST_CODE = 2000;
	private static final int PARSE_BARCODE_SUC = 2001;
	private static final int PARSE_BARCODE_FAIL = 2002;
	private String photo_path;
	private Bitmap scanBitmap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_qrcode);
		if(getSupportActionBar()!=null){
			getSupportActionBar().hide();
		}
		
		back = (ImageView) findViewById(R.id.back);
		back.setOnClickListener(this);
		
		
		
	}

	@Override
	public void initView() {
		surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
	}

	@Override
	public void handDecodeMsg(String result) {
		// TODO Auto-generated method stub
		super.handDecodeMsg(result);

		if (result.equals("")) {
			Toast.makeText(QrCodeActivity.this, "Scan failed!",
					Toast.LENGTH_SHORT).show();
		} else {
			Intent it = getIntent();
			it.putExtra("code",result);
			setResult(RESULT_OK, it);
			this.finish();
		}

	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.back) {
			finish();
		}else if(v.getId() == R.id.more)
		{
			//打开手机中的相册
			Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
	        innerIntent.setType("image/*");
	        Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
	        this.startActivityForResult(wrapperIntent, REQUEST_CODE);
		}

	}

	
	
	
	private void showDialog(final String result)
	{
		
	}

//	private void show() {
//		if (loadingDialog == null) {
//			loadingDialog = LoadingDialog.createDialog(this);
//			loadingDialog.setCanceledOnTouchOutside(false);
//		}
//		loadingDialog.setMessage("请稍后...");
//		loadingDialog.show();
//	}
//
//	private void disMiss() {
//		if (loadingDialog != null) {
//			loadingDialog.dismiss();
//			loadingDialog = null;
//		}
//	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK){
			switch(requestCode){
			case REQUEST_CODE:
				//获取选中图片的路径
				Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
				if (cursor.moveToFirst()) {
					photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
				}
				cursor.close();
				
				new Thread(new Runnable() {
					@Override
					public void run() {
						Result result = scanningImage(photo_path);
						if (result != null) {
							Message m = mHandler.obtainMessage();
							m.what = PARSE_BARCODE_SUC;
							m.obj = result.getText();
							mHandler.sendMessage(m);
						} else {
							Message m = mHandler.obtainMessage();
							m.what = PARSE_BARCODE_FAIL;
							m.obj = "Scan failed!";
							mHandler.sendMessage(m);
						}
					}
				}).start();
				
				break;
			
			}
		}
	}
	
	
	/**
	 * 扫描二维码图片的方法
	 * @param path
	 * @return
	 */
	public Result scanningImage(String path) {
//		if(TextUtils.isEmpty(path)){
//			return null;
//		}
//		Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
//		hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码
//
//		BitmapFactory.Options options = new BitmapFactory.Options();
//		options.inJustDecodeBounds = true; // 先获取原大小
//		scanBitmap = BitmapFactory.decodeFile(path, options);
//		options.inJustDecodeBounds = false; // 获取新的大小
//		int sampleSize = (int) (options.outHeight / (float) 200);
//		if (sampleSize <= 0)
//			sampleSize = 1;
//		options.inSampleSize = sampleSize;
//		scanBitmap = BitmapFactory.decodeFile(path, options);
//		RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
//		BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
//		QRCodeReader reader = new QRCodeReader();
//		try {
//			return reader.decode(bitmap1, hints);
//
//		} catch (NotFoundException e) {
//			e.printStackTrace();
//		} catch (ChecksumException e) {
//			e.printStackTrace();
//		} catch (FormatException e) {
//			e.printStackTrace();
//		}
		return null;
	}
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			switch (msg.what) {
			case PARSE_BARCODE_SUC:
				showDialog((String)msg.obj);
				break;
			case PARSE_BARCODE_FAIL:
				Toast.makeText(QrCodeActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
				break;

			}
		}
		
	};

}